using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ObjectLib;
using StaticUtility;
using NumericalRecipes;
using BmgNet;
using EngMATLib;
using FftLib;

namespace DllTester
{
	/// <summary>
	/// Summary description for FormTest.
	/// </summary>
	public class FormTest : System.Windows.Forms.Form
	{
		private System.Windows.Forms.RichTextBox richTextBox1;
		private System.Windows.Forms.PictureBox Pb;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		public Bitmap Bmp=null;
		public PolygonF Pf;
		public PointF[] PfPb;
		public PointF[] RandomPoints;
		public PointF[] RandomPointsPb;
		public RectangleF ImgRect;
		
		public FormTest()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.Pb = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.Pb)).BeginInit();
            this.SuspendLayout();
            // 
            // richTextBox1
            // 
            this.richTextBox1.Location = new System.Drawing.Point(0,0);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(752,127);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "richTextBox1";
            // 
            // Pb
            // 
            this.Pb.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.Pb.Location = new System.Drawing.Point(0,133);
            this.Pb.Name = "Pb";
            this.Pb.Size = new System.Drawing.Size(588,481);
            this.Pb.TabIndex = 1;
            this.Pb.TabStop = false;
            this.Pb.Paint += new System.Windows.Forms.PaintEventHandler(this.Pb_Paint);
            this.Pb.SizeChanged += new System.EventHandler(this.Pb_SizeChanged);
            // 
            // FormTest
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
            this.ClientSize = new System.Drawing.Size(588,614);
            this.Controls.Add(this.Pb);
            this.Controls.Add(this.richTextBox1);
            this.Name = "FormTest";
            this.Text = "FormTest";
            this.Load += new System.EventHandler(this.FormTest_Load);
            ((System.ComponentModel.ISupportInitialize)(this.Pb)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new FormTest());
		}
		private void FormTest_Load(object sender, System.EventArgs e)
		{
			//TestRandomPolyPoint();
			//TestInverseAndEigs();
			//TestPngImage();
			//TestPngFloat();
			//TestPrimes();
			//TestPngUshort3();
			//TestIngMin();
			//RunKernelAnalysis2();
            //this.CheckNaturalGaborFilter(200,false);
            //this.CheckCrossOddFilter(200,true);
            CheckImagePixels();
		}
        public void CheckImagePixels()
        {
            ObjectParserData opd = ObjectParserData.Deserialize("E:\\2006-01-30 Edges And Shadows Finished (partial 1 to 3)\\97980972.ObjParser", null, SerializationType.Binary);
            int err;
            Ushort3 pix = Ushort3.FromPng16(opd.Imagename, out err);
            this.richTextBox1.Text = "";
            this.richTextBox1.AppendText("Fstop\t" + opd.Fstop.ToString() + "\n");
            this.richTextBox1.AppendText("Rate\t" + opd.ShutterRate.ToString() + "\n");
            this.richTextBox1.AppendText("Iso\t" + opd.IsoFilmSpeed.ToString() + "\n");
            this.richTextBox1.AppendText("Pfac\t" + opd.PixelFactor.ToString() + "\n");
            float[] rgb = new float[3];
            float[] loglms = new float[3];
            float[] lyr = new float[3];
            float fac = opd.PixelFactor;
            for (int i = 500; i < 520; i++)
            {
                this.richTextBox1.AppendText(i.ToString() + "," + i.ToString() + "\t" + pix[i, i, 0].ToString() + "\t" + pix[i, i, 1].ToString() + "\t" + pix[i, i, 2].ToString() + "\t");
                rgb[0] = fac * (float)pix[i, i, 0];
                rgb[1] = fac * (float)pix[i, i, 1];
                rgb[2] = fac * (float)pix[i, i, 2];
                KodakColorSpace.RgbToLogLms(rgb, loglms);
                KodakColorSpace.LogLmsToLumYbRg(loglms, lyr);
                this.richTextBox1.AppendText(
                    loglms[0].ToString() + "\t" +
                    loglms[1].ToString() + "\t" +
                    loglms[2].ToString() + "\t" +
                    lyr[0].ToString() + "\t" +
                    lyr[1].ToString() + "\t" +
                    lyr[2].ToString() + "\n");
            }
        }
        public void CheckNaturalGaborFilter(int quadSize, bool odd)
        {
            Complex2f filter = Complex2f.NaturalLogGabor(quadSize);
            Bmp = new Bitmap(filter.Nj, filter.Ni);
            filter.CalcStats();
            if(odd)
            {
                filter.ImprintImag(Bmp,1.0);
                Util.ImprintHorizontalBgwyr(Bmp,new RectangleF(0.0f,0.0f,(float)quadSize*2.0f,(float)quadSize/5.0f));
                Bmp.Save("C:/Odd.jpg",ImageFormat.Jpeg);
            }
            else
            {
                filter.ImprintReal(Bmp, 1.0);
                Util.ImprintHorizontalBgwyr(Bmp,new RectangleF(0.0f,0.0f,(float)quadSize*2.0f,(float)quadSize/5.0f));
                Bmp.Save("C:/Even.jpg",ImageFormat.Jpeg);
            }
        }
        public void CheckCrossOddFilter(int quadSize, bool odd)
        {
            Complex2f filter = Complex2f.Cross(quadSize);
            Bmp = new Bitmap(filter.Nj,filter.Ni);
            filter.CalcStats();
            if(odd)
            {
                filter.ImprintImag(Bmp,1.0);
                Util.ImprintHorizontalBgwyr(Bmp,new RectangleF(0.0f,0.0f,(float)quadSize*2.0f,(float)quadSize/5.0f));
                Bmp.Save("C:/CrossOdd.jpg",ImageFormat.Jpeg);
            }
            else
            {
                filter.ImprintReal(Bmp,1.0);
                Util.ImprintHorizontalBgwyr(Bmp,new RectangleF(0.0f,0.0f,(float)quadSize*2.0f,(float)quadSize/5.0f));
                Bmp.Save("C:/CrossEven.jpg",ImageFormat.Jpeg);
            }
        }
		public double ChisqTestFunc(double[] a)
		{
			double output = 0.0;
			for(int i=0; i<a.Length; i++)
				output+= a[i]*a[i];
			return output;
		}
		public void TestIngMin()
		{
			this.richTextBox1.Text = "";
			double[] a = new double[] {10.0, -8.0, 17.0, 1000.0, -1.0e5, -1.0};
			IngMin im = new IngMin(0.00001, a, new IngMin.DelChisq(ChisqTestFunc));
			int nSolve = im.Solve();
			this.richTextBox1.Text = this.richTextBox1.Text  + nSolve.ToString() + '\n' +  im.FullVerbose + '\n' + '\n';
		}
        /*
		public void RunKernelAnalysis2()
		{
			this.richTextBox1.Text = "";
			//int[] cols = new int[] {2, 3};
			//int[] cols = new int[] {0, 1, 2};
			//int[] cols = new int[] {3, 4, 5};
			//int[] cols = new int[] {6, 7, 8};
			string fname = @"C:\RibsForKernNs_128.mat";
			int[] cols;
			DistributionSet Dset;
			string colstr;
			bool removePriors = true;

			cols = new int[] {0, 1, 2};
			Dset = DistributionSet.FromMatFile2(fname, 2000, cols);
			Dset.SolveKsd(removePriors);
			colstr = cols[0].ToString();
			for(int i=1; i<cols.Length; i++)
				colstr = colstr + ", " + cols[i].ToString();
			this.richTextBox1.AppendText( fname +'\n' + colstr + '\n' + Dset.Stats);

			cols = new int[] {3, 4, 5};
			Dset = DistributionSet.FromMatFile2(fname, 2000, cols);
			Dset.SolveKsd(removePriors);
			colstr = cols[0].ToString();
			for(int i=1; i<cols.Length; i++)
				colstr = colstr + ", " + cols[i].ToString();
			this.richTextBox1.AppendText( fname +'\n' + colstr + '\n' + Dset.Stats);

			cols = new int[] {6, 7, 8};
			Dset = DistributionSet.FromMatFile2(fname, 2000, cols);
			Dset.SolveKsd(removePriors);
			colstr = cols[0].ToString();
			for(int i=1; i<cols.Length; i++)
				colstr = colstr + ", " + cols[i].ToString();
			this.richTextBox1.AppendText( fname +'\n' + colstr + '\n' + Dset.Stats);

			cols = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8};
			Dset = DistributionSet.FromMatFile2(fname, 2000, cols);
			Dset.SolveKsd(removePriors);
			colstr = cols[0].ToString();
			for(int i=1; i<cols.Length; i++)
				colstr = colstr + ", " + cols[i].ToString();
			this.richTextBox1.AppendText( fname +'\n' + colstr + '\n' + Dset.Stats);
			
		}
		public void RunKernelAnalysis()
		{
			KernAcc ka = KernAcc.FromMatFile(@"C:\RibsForKern_128.mat");
			ka.CountAndIndex();
			ka.PrepareSolveKsd();
			int[][,] confusion;
			double[][,] wmat, wmatFromNorm, jointLikelihood;
			int[][] nUncategorized;
			string txt;
			//ka.RunStats(out confusion, out wmat, out wmatFromNorm, out nUncategorized, out jointLikelihood, out txt);
			//this.richTextBox1.Text = txt;

			bool includePriors = true;
			//bool includePriors = false;
			
			//ka.SolveKsd(new int[] {0, 1, 2}, !includePriors);
			//ka.SolveKsd(new int[] {8}, !includePriors);
			//ka.SolveKsd(new int[] {3, 4, 5}, !includePriors);
			//ka.SolveKsd(new int[] {6, 7, 8}, !includePriors);
			ka.SolveKsd(new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8}, !includePriors);
			int nSolve = ka.Im.Ngoods;
			this.richTextBox1.Text = this.richTextBox1.Text  + nSolve.ToString() + '\n' +  ka.Im.FullVerbose + '\n' + '\n';

			ka.RunStats(out confusion, out wmat, out wmatFromNorm, out nUncategorized, out jointLikelihood, out txt);
			this.richTextBox1.Text = this.richTextBox1.Text  + txt;
			
		}
        */
		public void TestPngUshort3()
		{
			string filename = "C:\\Documents and Settings\\ing\\My Documents\\Visual Studio Projects\\Objects\\DllTester\\bin\\Debug\\97980972_48.png";
			int err;
			Ushort3 img = Ushort3.FromPng16(filename, out err);
			this.Bmp = img.AsBitmap(true);
		}
		public void TestPrimes()
		{
			EngMATLib.EngMATAccess mat = new EngMATLib.EngMATAccess();
			int[] p = Util.Primes(1721);
			double[,] dp = new double[p.Length,1];
			for(int i=0; i<p.Length; i++)
				dp[i,0] = (double)p[i];
			mat.SetMatrix("p", dp);
		}
		public void TestInverseAndEigs()
		{
			double[,] m = new double[2,2];
			m[0,0]=m[1,1]=17.0;
			m[1,0]=m[0,1]=8.0;
			/*
			double[,] m = new double[4,4];
			m[0,0] = 1.0668;
			m[0,1] = 0.2944;
			m[0,2] = -0.6918;
			m[0,3] = -1.4410;

			m[1,0] = 0.0593;
			m[1,1] = -1.3362;
			m[1,2] = 0.8580;
			m[1,3] = 0.5711;

			m[2,0] = -0.0956;
			m[2,1] = 0.7143;
			m[2,2] = 1.2540;
			m[2,3] = -0.3999;

			m[3,0] = -0.8323;
			m[3,1] = 1.6236;
			m[3,2] = -1.5937;
			m[3,3] = 0.6900;
			*/

			Nr.InverseDouble id = new Nr.InverseDouble();
			Nr.EigsDouble eigMem = new Nr.EigsDouble();

			double[,] output = new double[m.GetLength(0), m.GetLength(1)];
			Nr.InverseDouble.Run(m, output);

			double[,] eigVecs = new double[m.GetLength(0), m.GetLength(1)];
			double[] eigVals = new double[m.GetLength(0)];

			Nr.EigsDouble.RunRealSymmetric(m, m.GetLength(0), eigVals, eigVecs);

			richTextBox1.Text = "M=\n\n"+Util.MatrixToString(m)
				+ "\n\nInv(M)=\n\n" + Util.MatrixToString(output);

			//	Invoke the matlab engine to send data out.
			EngMATLib.EngMATAccess eng = new EngMATLib.EngMATAccess();
			eng.SetMatrix("M", m);
			eng.SetMatrix("Q", eigVecs);
			EngMATLib.Matrix dmat = new EngMATLib.Matrix(eigVals, 1);
			eng.SetMatrix("d", dmat);
		}
		public float ImgToPbX(float x)
		{
			return (x-ImgRect.Left) * (float)Pb.Width / ImgRect.Width;
		}
		public float ImgToPbY(float y)
		{
			return (y-ImgRect.Top) * (float)Pb.Height / ImgRect.Height;
		}
		public void TestPathStuff()
		{
			string a = "a:\\beta\\c\\delta\\homes.fart";
			string b = "a:\\beta\\slim\\douce.bag";
			
			string aa = "";
			string bb = "";
			string aaa = "";
			string bbb = "";
			//string aa = Util.Relativize(b,a);
			//string bb = Util.Relativize(a,b);

			//string aaa = Util.Absolutize(b,aa);
			//string bbb = Util.Absolutize(a,bb);

			this.richTextBox1.Text =
				"Relativization...\n"
				+  a + "  |to|  " + aa + '\n' 
				+  b + "  |to|  " + bb + '\n'
				+"Absolutization...\n"
				+  aa + "  |to|  " + aaa + '\n' 
				+  bb + "  |to|  " + bbb; 
		}
		public static ImageCodecInfo GetJpgCodec()
		{
			ImageCodecInfo[] ici = ImageCodecInfo.GetImageEncoders();
			int i=0;
			while(i<ici.Length)
			{
				if(ici[i].FilenameExtension.IndexOf("JPG")>=0)
					return ici[i];
				i++;
			}
			return null;
		}
		private void Pb_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{
			if(Pf!=null && RandomPoints!=null)	//	Paint method for TestRandomPolyPoint()
			{
				//	Draw the polygon
				int i;
				for(i=0; i<PfPb.Length; i++)
					PfPb[i] = new PointF(ImgToPbX(Pf[i].X), ImgToPbY(Pf[i].Y));
				e.Graphics.DrawPolygon(Pens.Blue,  PfPb);

				//	Draw the random points.
				for(i=0; i<RandomPoints.Length; i++)
				{
					RandomPointsPb[i] = new PointF(ImgToPbX(RandomPoints[i].X), ImgToPbY(RandomPoints[i].Y));
					e.Graphics.DrawEllipse(Pens.Red, RandomPointsPb[i].X-5.0f, RandomPointsPb[i].Y-5.0f, 10, 10);
				}
			}
			else if(Bmp!=null)
			{
				e.Graphics.DrawImage(Bmp, new Rectangle(0,0,Pb.Width,Pb.Height), 0,0,Bmp.Width,Bmp.Height,GraphicsUnit.Pixel);
			}
			else
				base.OnPaint(e);
		}
		private void Pb_SizeChanged(object sender, System.EventArgs e)
		{
			Pb.Invalidate();
		}
	}
}
